import { getphoneCode, Login, getLoginParam } from '@/api/path';
import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus'
import { SET_USER_INFO, GET_USER_INFO, REMOVE_USER_INFO } from '@/utils/user'

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    dialogVisible: false,
    code: '',
    userInfo: GET_USER_INFO(),
    loginParams: {}
  }),
  actions: {
    changeDialog(type: string) {
      if (type === 'open') {
        this.dialogVisible = true;
      } else {
        this.dialogVisible = false;
      }
    },
    async getCode(phone: string) {
      let res:any = await getphoneCode(phone)
      if (res.code === 200) {
        this.code = res.data
        return 'ok'        
      } else {
        return Promise.reject(res.message)
      }
    },
    async LoginFun(datas: any) {
      let data = datas
      let res: any = await Login(data)
      if (res && res.code === 200) {
        this.userInfo = res.data
        console.log(this.userInfo);
        
        ElMessage({
          type: 'success',
          message: res.message,
        })
        SET_USER_INFO(JSON.stringify(res.data) )
        return 'ok'
      } else {
        return Promise.reject(res && res.message)
      }
    },
    logout() {
      this.userInfo = {
        name: '',
        token: ''
      }
      console.log(this.userInfo, 'this.userInfo');
      
      REMOVE_USER_INFO()
    },
    async getLoginParams(url: string) {
      let res: any = await getLoginParam(url)
      if (res.code === 200) {
        this.loginParams = res.data
        // return 'ok'
      }
    },
    queryState() {
      let timer = setInterval(() => {
        if (GET_USER_INFO() && JSON.stringify(GET_USER_INFO()) !== '{}') {
          this.dialogVisible = false
          this.userInfo = GET_USER_INFO()
          clearInterval(timer)
        }
      }, 1000)
    }
  }

})